#include "native_app.h"
#include <QFileOpenEvent>
#include <QDebug>
#include <QUrl>
#include <QQmlEngine>
#include "log.h"
// CTKPluginFramework includes
#include "ctkPluginContext.h"
#include <ctkException.h>
#include "ctkPluginFrameworkLauncher.h"
#include "../mainwindow/mainwindowservice.h"
#include "common.h"

ActiveApp::ActiveApp(int &argc, char **argv)
    :QApplication(argc, argv)
{
    QCoreApplication::setOrganizationDomain("http://www.SodaGreen.com");
    QString curVersion = QString(APP_VERSION);
    curVersion = curVersion.mid(0, curVersion.lastIndexOf("."));
    QCoreApplication::setApplicationVersion(common::gVersionSymbol + curVersion);
    QCoreApplication::setApplicationName(common::getApplicationName());
    QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar);
    QCoreApplication::setOrganizationName("SodaGreen");
    Log::initLog();
    Log::writeDate(QString("TestCTK start!"), Log::INFO);

}

ActiveApp::~ActiveApp()
{
    Log::writeDate(QString("TestCTK end!"), Log::INFO);
}

void ActiveApp::argvParse(int argc, char** argv)
{
    qInfo() << "argc: " << argc;
//#ifdef Q_OS_WIN
    m_argvList = qApp->arguments();
    m_argvList.removeAt(0);
//#else
//    for (int i = 1; i < argc; i++) {
//        const std::string path = argv[i];
//        m_argvList.push_back(common::converseToUtf8(path));
//        //m_argvList.push_back(QString::fromLocal8Bit(argv[i]));
//        qInfo() << "argv i: " << i;
//        qInfo() << "argv value: " << m_argvList[i];
//    }
//#endif
}

const QStringList& ActiveApp::getFileList()
{
    return m_argvList;
}

bool ActiveApp::event(QEvent *event)
{
    //static int eventCount = 0;
    //qDebug() << "ActiveApp::event, event = " << event->type() << ", eventCount = " << eventCount++;
    if (event->type() == QEvent::Quit)
    {
        quitApp();
        event->ignore();
    }

    return QObject::event(event);
}

bool ActiveApp::notify(QObject * obj, QEvent * event)
{
    //qDebug() << "ActiveApp::notify, obj" << obj->objectName() << ", className = " << obj->metaObject()->className() << ", event = " << event;
    return QApplication::notify(obj, event);
}

void ActiveApp::quitApp()
{
    ctkPluginContext *context = ctkPluginFrameworkLauncher::getPluginContext();
    ctkServiceReference ref = context->getServiceReference<MainWindowService>();
    if (ref) {
        MainWindowService* mainWindow = context->getService<MainWindowService>(ref);
        if (mainWindow != nullptr) {
            mainWindow->quitApp();
            context->ungetService(ref);
            qInfo("ActiveApp quit.");
        }
    } else {
        qFatal("quitApp is faild.");
    }
}

